<template>
  <el-container>
    <el-header>
      <div class="header-content">
        <DetailHeader />
      </div>
    </el-header>
    <el-main>
      <div id="container"></div>
      <div class="middle">
        <el-timeline class="timeline" style="max-width: 600px">
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :icon="activity.icon"
            :type="activity.type"
            :color="activity.color"
            :size="activity.size"
            :hollow="activity.hollow"
            :timestamp="activity.timestamp"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>

        <div class="trans-status">
          <div class="tip-wrap">
            <i class="iconfont i-first">&#xe606;</i>
            <span style="font-weight: bold">运输状态</span>
          </div>
          <div class="specific-info-wrap">
            <div class="step">
              <el-steps :active="active" finish-status="success">
                <el-step title="已发货" />
                <el-step title="运输中" />
                <el-step title="签收"
              /></el-steps>
            </div>
            <div class="truck-wrap">
              <div v-show="active === 0"><img :src="shipTruckUrl" alt="" /></div>
              <div v-show="active === 1"><img :src="shipTruckUrl" alt="" /></div>
              <div v-show="active === 2"><img :src="shipTruckUrl" alt="" /></div>
            </div>
          </div>
        </div>
      </div>

      <div class="content">
        <div id="person_info">
          <div>
            <div>
              <i class="iconfont i-first">&#xe606;</i>
              <span>人员详情</span>
            </div>
          </div>
          <div>
            <div id="avatar">
              <div>
                <el-avatar fit="cover" :size="60">
                  <img :src="courierWrap.courierAvatar" />
                </el-avatar>
              </div>
            </div>
            <div id="info">
              <div>
                <span>快递员</span> <span>{{ courierWrap.courierName }}</span>
              </div>
              <div>
                <div>
                  <span>{{ courierWrap.carNumber }}</span>
                </div>
                <div><i class="iconfont i-second">&#xe627;</i><span>任务中</span></div>
              </div>
            </div>
          </div>
          <div>
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <div><span>任务类型</span></div>
                  <div>
                    <div>
                      <i class="iconfont i-third">&#xe713;</i
                      ><span>{{ courierWrap.areaName }}</span>
                    </div>
                    <div><span>2024-02-08 12:13:04</span></div>
                  </div>
                </div>
              </template>
              <div class="infowrap">
                <div>
                  车辆编号：<span>{{ courierWrap.carId }}号车</span>
                </div>
                <div>
                  任务终点：<span>{{ courierWrap.destination }}</span>
                </div>
                <div>
                  累计用时：<span>{{ courierWrap.timeConsume }}</span>
                </div>
                <div>用户要求送货时间：工作日、节假日都可</div>
              </div>

              <div>
                <div><span id="objectImg">物品图片</span></div>
                <div id="objectInfo">
                  <div v-for="item in objectList" :key="item.id">
                    <img :src="item.url" alt="" />
                  </div>
                </div>
              </div>
              <template #footer>
                <div id="notes">
                  <span>备注：</span>
                  <div>
                    <p>{{ courierWrap.moreInfo }}</p>
                  </div>
                </div>
              </template>
            </el-card>
          </div>
        </div>
        <div id="right_wrap">
          <div id="tip">
            <i class="iconfont i-first">&#xe606;</i>
            <span style="font-weight: bold">客户留言</span>
          </div>

          <div id="chatwrap">
            <ChatWindow></ChatWindow>
          </div>
        </div>
      </div>
    </el-main>
    <el-footer>
      <Bottom />
    </el-footer>
  </el-container>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, markRaw } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import ChatWindow from "@/components/ChatWindow.vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import DetailHeader from "@/components/DetailHeader.vue";
import { MoreFilled, Location, OfficeBuilding } from "@element-plus/icons-vue";
import Bottom from "@/components/Bottom.vue";
import { objectImgs } from "@/common/common";
const route = useRoute();
const shipTruckUrl = "https://cityexpress.yellowswimming.cn/img/truck.png";

const activities = reactive([
  {
    content: "北京南站路出发",
    timestamp: "2018-04-12 20:46",
    size: "large",
    color: "skyblue",
    hollow: true,
    icon: markRaw(Location),
  },
  {
    content: "北京科技大学",
    timestamp: "2018-04-03 20:46",
    size: "large",
    type: "primary",
    icon: markRaw(MoreFilled),
  },
  {
    content: "四川入拣处",
    timestamp: "2018-04-03 20:46",
    size: "large",
    type: "primary",
    icon: markRaw(MoreFilled),
  },
  {
    content: "重庆渝北",
    timestamp: "2018-04-03 20:46",
    size: "large",
    type: "primary",
    icon: markRaw(MoreFilled),
  },
  {
    content: "正在派送...",
    timestamp: "2018-04-03 20:46",
    size: "large",
    type: "success",
    icon: markRaw(OfficeBuilding),
  },
]);
const active = ref<number>(2);
const routingTracking = reactive({
  originX: null,
  originY: null,
  destinationX: null,
  destinationY: null,
  start: "",
  end: "",
});
const objectList = reactive(objectImgs);

const getRandomPositiveInteger = (min: number, max: number): number => {
  // 使用 Math.random() 生成一个0到1之间的随机数
  const randomNum: number = Math.random();
  // 将随机数乘以范围，加上最小值，然后向下舍入到最接近的整数
  const randomInteger: number = Math.floor(randomNum * (max - min + 1)) + min;
  return randomInteger;
};

let map: any = null;
//高德地图
window._AMapSecurityConfig = {
  securityJsCode: "c02dfcaa54646f3345a653cf3c2ee8ed",
};

const initMap = async () => {
  AMapLoader.load({
    key: "7544d175c9e5b1d21ade87b5bed47f52", //申请好的Web端开发者 Key，调用 load 时必填
    version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
    plugins: [
      "AMap.ToolBar",
      "AMap.Scale",
      "AMap.ControlBar",
      "AMap.Geolocation",
      "AMap.HawkEye",
      "AMap.MapType",
      "AMap.Driving",
    ],
  })
    .then((AMap) => {
      map = new AMap.Map("container", {
        pitch: 50, //地图俯仰角度，有效范围 0 度- 83 度
        viewMode: "3D", //地图模式
        rotateEnable: true, //是否开启地图旋转交互 鼠标右键 + 鼠标画圈移动 或 键盘Ctrl + 鼠标左键画圈移动
        pitchEnable: true, //是否开启地图倾斜交互 鼠标右键 + 鼠标上下移动或键盘Ctrl + 鼠标左键上下移动
        zoom: 15, //初始化地图层级
        rotation: -15, //初始地图顺时针旋转的角度
        zooms: [2, 20], //地图显示的缩放级别范围
        resizeEnable: true,
        terrain: true, //开启地形图
        center: [116.397428, 39.90923], //地图中心点
      });

      map.on("complete", function () {
        console.log("地图加载完成"); //地图图块加载完成后触发
      });
      let driving = new AMap.Driving({
        policy: 0, //驾车路线规划策略，0是速度优先的策略
        map: map,
      });
      let passRouteId = null;
      let passX: any = null;
      let passY: any = null;
      let passLocation: any = "";
      var startLngLat = [routingTracking.originX, routingTracking.originY]; //起始点坐标
      var endLngLat = [routingTracking.destinationX, routingTracking.destinationY]; //终点坐标

      driving.search(startLngLat, endLngLat, function (status: any, result: any) {
        if (status === "complete") {
          console.log("绘制驾车路线完成 = ", result.routes[0].steps);
          let len = result.routes[0].steps.length;
          passRouteId = getRandomPositiveInteger(4, len - 1);
          passX = result.routes[0].steps[passRouteId].tmcsPaths[0].path[0].lng;
          passY = result.routes[0].steps[passRouteId].tmcsPaths[0].path[0].lat;
          passLocation = result.routes[0].steps[passRouteId].road;
          activities[0].content = routingTracking.start;
          let downbound = 2;
          let maxCnt = 20;
          for (let i = 1; i < 5; i++) {
            if (maxCnt <= 0) break;
            maxCnt--;
            let randomNum: number = getRandomPositiveInteger(downbound, len - 1);
            console.log(result.routes[0].steps[randomNum].road);
            if (
              result.routes[0].steps[randomNum].road === activities[i - 1].content ||
              result.routes[0].steps[randomNum].road === ""
            ) {
              i--;
              continue;
            }
            activities[i].content = result.routes[0].steps[randomNum].road;
            downbound = randomNum + 1;
          }
          map.setCenter([routingTracking.originX, routingTracking.originY]);
          map.addControl(driving);
        } else {
          console.log("获取驾车数据失败：", result);
        }
      });

      let startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(67, 39),
        // 图标的取图地址
        image: shipTruckUrl,
        // 图标所用图片大小
        imageSize: new AMap.Size(67, 39),
      });

      // 将 icon 传入 marker
      setTimeout(() => {
        console.log("passX = ", passX);
        console.log("passY = ", passY);
        let startMarker = new AMap.Marker({
          position: new AMap.LngLat(passX, passY),
          icon: startIcon,
        });
        //创建点标记的点击事件
        startMarker.on("click", function (e: any) {
          map.setFitView(startMarker);
        });
        // label默认蓝框白底左上角显示，样式className为：amap-marker-label
        startMarker.setLabel({
          direction: "right",
          offset: new AMap.Pixel(10, 0), //设置文本标注偏移量
          content: `<div class='info'">您的快递目前已经到了${passLocation}</div>`, //设置文本标注内容
        });
        map.setFitView(startMarker);
        map.add(startMarker);
      }, 2000);

      //异步加载控件
      map.addControl(new AMap.Scale());
      map.addControl(new AMap.ToolBar());
      map.addControl(new AMap.HawkEye());
      map.addControl(new AMap.MapType());
      map.addControl(new AMap.Geolocation());
      map.addControl(new AMap.ControlBar());
    })
    .catch((e) => {
      console.error(e); //加载错误提示
    });
};

const initRouteTrack = async (id: any) => {
  const response = await axios.get(`http://localhost:8085/route/getRoute/${id}`);
  console.log("response data===", response);
  routingTracking.originX = response.data.originX;
  routingTracking.originY = response.data.originY;
  routingTracking.destinationX = response.data.destinationX;
  routingTracking.destinationY = response.data.destinationY;
  routingTracking.start = response.data.start;
  routingTracking.end = response.data.end;
};
const courierWrap: any = reactive({
  courierAvatar: "",
  areaName: "",
  courierName: "",
  carNumber: "",
  currentPos: "",
  carId: "",
  destination: "",
  timeConsume: "",
  moreInfo: "",
});
const getAreaName = async () => {
  const response = await axios.get(
    `http://localhost:8090/courier/getAreaName/${route.params.orderId}`
  );
  courierWrap.areaName = response.data;
  console.log(courierWrap.areaName);
};
const getCourierNameAndAvatar = async () => {
  let response = await axios.get(
    `http://localhost:8085/order/getCourierNameByOrderId/${route.params.orderId}`
  );
  courierWrap.courierName = response.data;
  response = await axios.get(
    `http://localhost:8180/user/getAvatar/${courierWrap.courierName}`
  );
  courierWrap.courierAvatar = response.data;
};
const getVehicle = async () => {
  console.log("courierWrap.courierName = ", courierWrap.courierName);
  const response = await axios.get(
    `http://localhost:8089/vehicle/getVehicleByCourierName/${courierWrap.courierName}`
  );
  courierWrap.carNumber = response.data.licensePlate;
  courierWrap.carId = response.data.vehicleId;
};
const getRouteDestination = async () => {
  let response = await axios.get(
    `http://localhost:8089/routePlan/getDesByOrderId/${route.params.orderId}`
  );
  courierWrap.destination = response.data;
};
const getOrderByOrderId = async () => {
  let response = await axios.get(
    `http://localhost:8085/order/getByOrderId/${route.params.orderId}`
  );
  courierWrap.moreInfo = response.data.moreInformation;
};
onMounted(async () => {
  await initRouteTrack(route.params.orderId);
  await getAreaName();
  await getCourierNameAndAvatar();
  await getVehicle();
  await getRouteDestination();
  await getOrderByOrderId();
  console.log("routingTracking = ", routingTracking);
  await initMap();
});
</script>

<style scoped lang="less">
@font-face {
  font-family: "iconfont";
  /* Project id 4410292 */
  src: url("//at.alicdn.com/t/c/font_4410292_nakk71welt.woff2?t=1707986927712")
      format("woff2"),
    url("//at.alicdn.com/t/c/font_4410292_nakk71welt.woff?t=1707986927712") format("woff"),
    url("//at.alicdn.com/t/c/font_4410292_nakk71welt.ttf?t=1707986927712")
      format("truetype");
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;
}

#container {
  margin: 0 auto;
  width: 97%;
  height: 80vh;
}

.middle {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 50px;

  .timeline {
    flex: 1;
  }

  .trans-status {
    flex: 1.5;
    margin-right: 10px;
    height: 50vh;

    .tip-wrap {
      margin-bottom: 15px;
      display: flex;

      .i-first {
        color: blue;
      }
    }

    .specific-info-wrap {
      height: 50%;

      .step {
        height: 20%;
        width: 80%;
      }

      .truck-wrap {
        margin-top: 1.5rem;
        height: 25%;
        position: relative;
        width: 80%;

        > div {
          position: absolute;
          width: 9%;
          height: 100%;

          img {
            height: 100%;
            width: 100%;
            object-fit: cover;
          }
        }

        > div:nth-child(1) {
          left: 0rem;
        }

        > div:nth-child(2) {
          left: 20rem;
        }

        > div:nth-child(3) {
          right: -1rem;
        }
      }
    }
  }
}

.content {
  display: flex;
  height: 77vh;

  #person_info {
    flex: 1;
    margin-top: 1rem;
    height: 98%;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;

    > div:first-child {
      flex: 0.5;
      display: flex;
      margin-bottom: 10px;
      justify-content: flex-start;
      align-items: center;

      > div {
        height: 58%;
        margin-left: 0.6rem;
        display: flex;
        align-items: center;

        .i-first {
          color: blue;
          font-size: 2rem !important;
        }

        span {
          font-size: 1.3rem;
          font-weight: 700;
        }
      }
    }

    > div:nth-child(2) {
      height: 17%;
      display: flex;
      align-items: center;
      justify-content: flex-start;

      #avatar {
        width: 30%;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      #info {
        width: 60%;
        display: flex;
        flex-direction: column;
        justify-content: center;

        > div:nth-child(1) {
          margin-top: 0.4rem;

          span {
            margin-right: 1rem;
            font-size: 1rem;
            font-weight: bold;
          }
        }

        > div:nth-child(2) {
          display: flex;
          margin-top: 1rem;
          font-size: 0.9rem;
          height: 50%;

          > div:nth-child(1) {
            width: 40%;
            height: 55%;
            display: flex;
            justify-content: center;
            align-items: center;
            background: linear-gradient(to bottom, #c2d5ff, white);
          }

          > div:nth-child(2) {
            margin-left: 1rem;
            width: 30%;
            height: 55%;
            display: flex;
            justify-content: center;
            align-items: center;
            background: linear-gradient(to bottom, #cffcc1, #ebfce2);

            .i-second {
              color: green !important;
            }
          }
        }
      }
    }

    > div:nth-child(3) {
      height: 70vh;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 1.3rem;

      .box-card {
        width: 100%;
        height: 100%;
        background-color: #f3f7ff;
      }

      .card-header {
        height: 12vh;
        display: flex;
        flex-direction: column;
        justify-content: space-around;

        > div:nth-child(1) {
          span {
            color: #a0a3a7;
            font-size: 0.9rem;
          }
        }

        > div:nth-child(2) {
          display: flex;
          justify-content: space-between;

          > div:nth-child(1) {
            span {
              font-weight: bold;
            }
          }

          > div:nth-child(2) {
            span {
              font-size: 0.9rem;
              color: #a0a3a7;
            }
          }

          .i-third {
            color: blue;
          }
        }
      }

      .infowrap {
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;

        > div {
          margin-bottom: 0.3rem;
          font-size: 0.8rem;
          color: #a0a3a7;
        }
      }

      #objectImg {
        font-size: 0.9rem;
        color: #a0a3a7;
      }

      #notes {
        color: #a0a3a7;
        font-size: 0.9rem;
      }

      #objectInfo {
        height: 10vh;
        display: flex;
        justify-content: flex-start;

        > div {
          width: 25%;
          padding: 0 10px 0 10px;

          margin-top: 1rem;
        }

        img {
          border-radius: 0.6rem;
          height: 100%;
          width: 100%;
          object-fit: cover;
        }
      }
    }
  }

  #right_wrap {
    padding-left: 10px;
    margin-top: 1rem;
    flex: 3;
    height: 98%;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    #tip {
      height: 10%;
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .i-first {
        color: blue;
        font-size: 2rem !important;
        padding-right: 5px;
      }
    }

    #chatwrap {
      height: 84vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
